package com.heima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.mapper.WmNewsMaterialMapper;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dto.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.mapper.WmMaterialMapper;
import com.heima.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.*;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.oss.prefix}")
    String prefix;
    @Autowired
    FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) throws IOException {
        //检查参数
        if (multipartFile.getSize()<0||multipartFile==null)
        {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        //登录用户是否存在
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        String originalFilename = multipartFile.getOriginalFilename();
        if(!checImageType(originalFilename)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID ,"请上传正确的图片格式");
        }
        String filename = UUID.randomUUID().toString().replaceAll("-", "");
        String s = originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传文件到oss
        String path = fileStorageService.store(prefix, filename + s, multipartFile.getInputStream());

        // 向wmmaterial插入一条数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short) 0);//不收藏
        wmMaterial.setType((short) 0);//0 为图片
        wmMaterial.setUrl(path);//文件的url
        //返回结果，将成功保存的素材返回给前端，将urL添加前缀
        save(wmMaterial);
        wmMaterial.setUrl(webSite+path);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 对上传的文件得到后缀进行进行检查
     * @param originalFilename
     * @return
     */
    private boolean checImageType(String originalFilename) {
        if (StringUtils.isBlank(originalFilename)){
            return false;
        }
        ArrayList<String> list = new ArrayList<>();
        Collections.addAll(list,"jpg", "jpeg", "png", "gif");
    boolean isAllow =false;
    for (String s : list) {

        if (originalFilename.endsWith(s)){
            isAllow = true;
            break;
        }
    }
    return isAllow;
    }


    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        //检查参数
        dto.checkParam();
        //判断前台传过来得条件，如果传来的是1我们根据这个状态去查询数据库
        Short isCollection = dto.getIsCollection();
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();
        if(isCollection!=null&&isCollection==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请登录");
        }
        //按照发布时间进行排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        //进行分页
        IPage<WmMaterial> requPage = new Page<>(dto.getPage(),dto.getSize());

        IPage<WmMaterial> page = page(requPage, wrapper);
        List<WmMaterial> records = page.getRecords();
        //加上前缀
        for (WmMaterial record : records) {

            record.setUrl(webSite+record.getUrl());
    }
        //封装返回的结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),records);

        httt://heima1322.oss-cn-shanghai.aliyuncs.com/material/2021/9/20210924/7da59b0dfc084487bb5512872e850388.jpg
        return responseResult;
    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        //检查参数
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        //查询是否有该图片
        WmMaterial wmMaterial = this.getById(id);
        if (wmMaterial==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询是否关联其他库
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count>0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //删除数据库的
        this.removeById(id);
        //删除oss的库
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"图片不存在");
        }
        LambdaUpdateWrapper<WmMaterial> wrapper = Wrappers.lambdaUpdate();
        //根据id和登录用户的id来取消或者关注
        Integer uid = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId,uid)
                .eq(WmMaterial::getId,id)
                .set(WmMaterial::getIsCollection,type);
        update(wrapper);
        return ResponseResult.okResult();
    }

}
